'use strict';

import React, {Component, PropTypes} from 'react';
import {IMG} from '../res';
import CropperJS from 'react-cropperjs';

export default class Avatar extends Component {
	/*
	 * 构造函数。
	 * @param props 只读属性
	 */
	constructor(props) {
		super(props);
		this.state = {};
	}

	/*
	 * 获取头像base64。
	 */
	getBase64() {
		return this.refs.img.src;
	}

	/*
	 * 选择文件后。
	 */
	_onInputChange() {
		let file = this.refs.file.files[0];
		if (!/\.(png|jpg|jpeg|bmp)$/.test(file.name)) {
			alert('Oops...不支持' + file.name);
		} else {
			let reader = new FileReader();
			reader.onload = e => {
				this.setState({
					file: e.target.result
				});
			}
			reader.readAsDataURL(file);
		}
	}

	/*
	 * 点击头像。
	 * @param e 事件
	 */
	_onImgClick(e) {
		if (this.props.editable) {
			this.refs.file.click();
		}
	}

	/*
	 * 裁剪时。
	 */
	_onCrop() {
		const base64 = this.refs.cropper.getCroppedCanvas().toDataURL('image/jpeg', 0.5);
		this.refs.img.src = base64;
	}

	/*
	 * 渲染视图。
	 */
	render() {
		const cropperLength = 200;
		const imgLength = 80;

		const {
			src,
			editable
		} = this.props;

		const {
			file
		} = this.state;

		const divStyle = {
			display: 'inline-block',
			width: this.props.width || 300,
			marginBottom: 10
		};

		const cropperStyle = {
			display: !file ? 'none' : 'inline'
		};

		const imgStyle = {
			width: imgLength,
			height: imgLength,
			cursor: editable ? 'pointer' : 'auto',
			borderRadius: imgLength
		};

		return (
			<div style={divStyle}>
				<img 
					src={src || IMG.avatar}
					ref='img'
					onClick={this._onImgClick.bind(this)}
					style={imgStyle}
				/>
				<CropperJS
					ref='cropper'
					src={file}
					style={cropperStyle}
					aspectRatio={1 / 1}
					crop={this._onCrop.bind(this)} 
					minContainerWidth={cropperLength}
					minContainerHeight={cropperLength}
				/>
				<input 
					type='file'
					className='am-hide'
					ref='file'
					onChange={this._onInputChange.bind(this)}
				/>
			</div>
		);
	}
}

Avatar.propTypes = {
	width: PropTypes.number,
	src: PropTypes.string,
	editable: PropTypes.bool
};
Avatar.defaultProps = {};
